﻿/*
    跟随对话框
*/
var hasFollow = 0;//指示是否已经跟随
var hasOpendOrder = false;
$(".follow_type1").click(function () {
    if ($(this).hasClass('readonly')) {
        msg('您正在跟随该交易员，不支持修改跟随方式', 1);
        return;
    }
    $(".follow_type1").removeClass('follow_active');
    $(this).addClass('follow_active');
    if ($(this).attr('follow-type') === '0') {
        $("#FixedNum").parent().show();
        $("#RateNum").parent().hide();
        $("#StrategyType").val("1");
    } else {
        $("#RateNum").parent().show();
        $("#FixedNum").parent().hide();
        $("#StrategyType").val("2");
    }
    $("#currentChoose").text($(this).next().find(".follow-setup-input").attr("prefix"));

});
$(".follow_type2").click(function () {
    $(".follow_type2").removeClass('follow_active');
    $(this).addClass('follow_active');
    $("#followDirect").text($(this).attr("prefix"));
    $("#Direction").val($(this).attr("dirval"));
});

$("#RateNum,#FixedNum").change(function () {
    //updateStrategyTip($(this));
});

function updateStrategyTip(obj) {
    $("#currentChoose").text(obj.attr("prefix") + obj.val() + obj.attr("unit"));
}

function showFollowDlg(tid,index) {
    requiredLogin(onShowFollowDlg, tid+"_"+index+"_0");//最后的【_0】用来标识点击“跟随/编辑跟随”按钮打开弹框页面
}

//显示跟随设置弹框页面
//initAccount：是否重新初始化Account信息，  0-否  undefined-是
function onShowFollowDlg(tid,initAccount) {
    var tuserid = 0;
    var traderAccountIndex = 0;
    var followerAccountIndex = 0;
    var newOpen = 0;
    if (tid != null && tid != undefined) {
        tuserid = tid.split("_")[0];
        traderAccountIndex = tid.split("_")[1];
        newOpen = tid.split("_")[2];//【newOpen=underfined时，标识下拉框列表点击触发的该方法】
    }

    if (newOpen == undefined)  {
        //dropList切换账号初始化跟随设置弹框
        followerAccountIndex=$("#FollowerAccountIndex").val();
    }

    //设置遮罩层loading
    loadingAnimation = true;
    hasFollow = 0;
    hasOpendOrder = false;
    //点击跟随时重新初始化账户信息
    
    if (initAccount == undefined)
    {
        InitAccountList();
    }
    
    $.post(GetFollowUrl, { 't': ticker(), 'traderId': tuserid, 'traderAccountIndex': traderAccountIndex, "followerAccountIndex": followerAccountIndex }, function (data) {
        if (data.code == 0) {
            setExistsFollow(data.follow);
            hasFollow = 1;
            hasOpendOrder = data.opendOrder;
            $("#TraderBrokerId").val(data.traderBrokerid);
            $("#FollowerBrokerId").val(data.customerBrokerid);
        }
        //显示或隐藏取消跟随按钮
        if (data.exists == 0) {
            $("#cancelBtn").hide();
            $(".follow_type1").removeClass('readonly');
        }
        else {
            $(".follow_type1").addClass('readonly');
            $("#cancelBtn").show();
        }

        //跨经纪商跟随显示风险提示
        if ($("#FollowerBrokerId").val() == 3 || $("#TraderBrokerId").val() != $("#FollowerBrokerId").val()) {
            $("#message").show();
        }
        else {
            $("#message").hide();
        }
        GetUserAccountInfo(followerAccountIndex);
    });
    
    

    $("#TraderAccountIndex").val(traderAccountIndex);   
    $("#follow_Dlg").fadeIn();
    $("#TraderID").val(tuserid);
}

//点击跟随时重新初始化账户信息
function InitAccountList()
{
    $.post(GetAccountUrl,
        {},
        function (data) {
            //初始化当前帐号信息
           var uaHtml = '';
            if (data.userAccount.BrokerId == 0)
            {
                uaHtml += '';
            }
            else if (data.userAccount.BrokerId == 3) {
                uaHtml += '<span class="typeimgbox broker-logo-type"><span class="mark_icon  mark_icon8_3" style="margin-left:5px;"><img src="/Themes/DefaultClean/Images/broker/3_15_15.png"> </span></span>模拟账户';
            }
            else {
                uaHtml += '<span class="typeimgbox broker-logo-type"><span class="mark_icon  mark_icon8_3" style="margin-left:5px;"><img src="/Themes/DefaultClean/Images/broker/'
                uaHtml += data.userAccount.BrokerId + '.png"></span></span>' ;
                uaListHtml += data.userAccount.MT4Account + '<span style="color:#999"> - ';
                uaListHtml += data.userAccount.UserType == 1 ? '交易员' : '跟随者';
            }
            $("#AccountDropDownList").html(uaHtml);
            //加载当前用户的经纪商和交易帐号编号
            $("#FollowerBrokerId").val(data.userAccount.BrokerId);
            $("#FollowerAccountIndex").val(data.userAccount.AccountIndex);

            //初始化帐号列表信息
            var uaListHtml = '';
            for (var i = 0; i < data.userAccountList.length ; i++)
            {
                uaListHtml += '<li class="js_choiceAccount" id="' + data.userAccount.UserId + '_' + data.userAccountList[i].AccountIndex + '" onclick="AccountListClick(this);"><span class="typeimgbox">';
                if (data.userAccountList[i].BrokerId == 3) {
                    uaListHtml += '<span class="mark_icon  mark_icon8_3" style="margin-left:5px;"><img src="/Themes/DefaultClean/Images/broker/3_15_15.png"> </span></span>模拟账户</li>';
                }
                else {
                    uaListHtml += '<span class="mark_icon  mark_icon8_3" style="margin-left:5px;" ><img src="/Themes/DefaultClean/Images/broker/';
                    uaListHtml += data.userAccountList[i].BrokerId + '.png"> </span></span>';
                    uaListHtml += data.userAccountList[i].MT4Account + '<span style="color:#999"> - ';
                    if (data.userAccountList[i].BrokerId == 6)
                    {
                        uaListHtml += 'mini - ';
                    }
                    uaListHtml += data.userAccountList[i].UserType == 1 ? '交易员' : '跟随者';
                    uaListHtml += '</span></li>';
                }
            }
            $("#uaList").html(uaListHtml);

            $("#AccountDropDownList,.js_AccountDropI").click();
        });


}

function hideFollowDlg() {
    $('#follow_Dlg').fadeOut();
    //设置遮罩层loading
    loadingAnimation = false;

    //隐藏取消跟随按钮、跨经纪商跟随风险提示信息
    $("#cancelBtn").hide();
    $("#message").hide();
}

$(document).ready(function () {
    onDigChanged($("#RateNum"));
    onDigChanged($("#FixedNum"));

    confirmFollow();
    cancelFollow();
});

function onDigChanged(obj) {
    obj.on("blur", function () {
        var curAmount = obj.val().trim();
        if (!isNaN(parseFloat(curAmount))) {
            if (parseFloat(curAmount) < 0) {
                obj.val("");
            }
            else {
                obj.val(parseFloat(curAmount).toFixed(2));
            }
        }
        else {
            obj.val('');
        }
        updateStrategyTip($(this));
    });
}

function confirmFollow() {
    $("#confirmBtn").click(function () {
        //if (USER_NAME == undefined || USER_NAME == "" || USER_NAME == null) {
        //    msg("请设置昵称！");
        //    return;
        //}
        var followSetting = $("#StrategyType").val() == "1" ? $("#FixedNum").val() : $("#RateNum").val();
        if (followSetting == '') {
            msg($("#StrategyType").val() == "1" ? '请输入正确的手数！' : '请输入正确的倍数！', 1);
            return;
        }
        $("#FollowSetting").val(followSetting);
        postData("followDlgForm", FollowUrl, "confirmBtn", function (data) {
            if (data.code == 0) {
                //刷新跟随状态
                attentionUserByFollow();
                msg("跟随设置成功！")
                $('#follow_Dlg').fadeOut();
                if (window["onConfirmFollow"] != undefined) {
                    //hasFollow=0:新跟随  1:编辑跟随
                    window["onConfirmFollow"](hasFollow);
                }
            } else {
                msg(data.message, 3);
            }
        });
    });
}

//跟随后关注
function attentionUserByFollow() {
    var userId = $("#TraderID").val();
    $.post("/Social/Blog/OnlyAttentionUser", { id: userId }, function (data) {
        getUserAssociate();
    });
}

function cancelFollow() {
    $("#cancelBtn").click(function () {
        if (hasOpendOrder)
        {
            confirmBox("您跟随此交易员有未平仓单，停止跟随后此平仓单将在交易员平仓后自动平仓。是否确定停止跟随？", executeCancel, 0);
        }
        else
            executeCancel();
    });
}

function executeCancel()
{
    postData("followDlgForm", StopFollowUrl, "cancelBtn", function (data) {
        if (data.code == 0) {
            //刷新跟随状态
            getUserAssociate();
            msg("已停止跟随该交易员！")
            $('#follow_Dlg').fadeOut();
            if (window["onCancelFollow"] != undefined) {
                window["onCancelFollow"]();
            }
        } else {
            msg(data.message);
        }
    });
}

/*
设置已存在的跟随信息
*/
function setExistsFollow(obj) {
    //设置跟随
    $(".follow-setup-cn-box").removeClass("follow_active");
    $(".follow-setup-input").parent().hide();
    $("#Direction" + obj.Direction).addClass("follow_active");
    $("#StrategyType" + obj.StrategyType).addClass("follow_active");
    $(".follow-setup-input").val('');

    $(".follow-setup-input[set='" + obj.StrategyType + "']").val(obj.FollowSetting).parent().show();
    //$(".follow-setup-input[set='" + obj.StrategyType + "']").val(obj.FollowSetting);
    //$(".follow_type" + obj.StrategyType).trigger("click");    
    $("#StrategyType").val(obj.StrategyType);
    $("#Direction").val(obj.Direction);
    $("#followDirect").text($("#Direction" + obj.Direction).attr("prefix"));
    $("#currentChoose").text(obj.StrategyType == 1 ? "固定数量下单" : "按比例下单");
    
    if (obj.LimitOrdersNum != 0) {
        $("#limitOrdersNum").val(obj.LimitOrdersNum);
    }
    else {
        $("#limitOrdersNum").val("");
    }
    if (obj.LimitVolume != 0) {
        $("#limitVolume").val(obj.LimitVolume);
    }
    else {
        $("#limitVolume").val("");
    }
    if (obj.LimitLossMoney != 0) {
        $("#limitLossMoney").val(obj.LimitLossMoney);
    }
    else {
        $("#limitLossMoney").val("");
    }

    if (obj.ExceptiveTimeFrame != null && obj.ExceptiveTimeFrame != "") {
        var timeZone = obj.ExceptiveTimeFrame.split("|");
        for (var i = 0; i < timeZone.length; i++) {
            if (timeZone[i] != undefined) {
                var zone1 = timeZone[i].split("-");
                if (zone1[0] != undefined) {
                    $("#timeFrom" + i).val(zone1[0].replace('_', ":"));
                }
                else {
                    $("#timeFrom" + i).val("");
                }
                if (zone1[1] != undefined) {
                    $("#timeTo" + i).val(zone1[1].replace('_', ":"));
                }
                else {
                    $("#timeTo" + i).val("");
                }
            }
            else {
                $("#timeFrom" + i).val("");
                $("#timeTo" + i).val("");
            }
        }
    }
    else {
        $("#timeFrom0").val("");
        $("#timeTo0").val("");
    }

   // $("#timeFrom").val(obj.LimitVolume);
}

//跟随设置弹框中交易帐号下拉列表点击事件
$("#AccountDropDownList,.js_AccountDropI").click(function () {
    if ($("#AccountSelectlist").is(':hidden')) {
        if ($('.choice_account_list').find('li').length != 1 && $('.choice_account_list').find('li').length != 0) {
            $("#AccountSelectlist").show();
        }
        else {
            $("[info='arrow']").hide();
        }
    }
    else {
        $("#AccountSelectlist").hide();
    }
});

//$(".js_AccountDropDownList").hover(function () {
//        $(this).mouseout(function () {
//            $("#AccountSelectlist").hide();
//        });
//    });

//跟随设置弹框交易订单下拉列表选中事件
$(".js_choiceAccount").click(function () {
    AccountListClick(this);
});

function AccountListClick(obj) {
    $("#AccountDropDownList").html($(obj).html());
    //当前选中跟随者【本人】交易账号的编号
    var followerAccountIndex = $(obj).attr("id").split("_")[1];
    $("#FollowerAccountIndex").val($(obj).attr("id").split("_")[1]);
    onShowFollowDlg($("#TraderID").val() + "_" + $("#TraderAccountIndex").val(),0);
    $("#AccountSelectlist").hide();
}


//根据当前登录用户的选中交易账号，获取该账号的最小手数等信息
//accountIndex=0时取当前启用的交易帐号信息
function GetUserAccountInfo(accountIndex) {
    $.ajax({
        type: "POST",
        url: "/Widget/GetUserAccountInfo",
        data: {  "accountIndex": accountIndex },
        success: function (data) {
            //console.log(data.minVolume);
            $("[info='minVolume']").text(data.minVolume);

            var dropListHtml = "";
            var brokerid = data.userAccount.BrokerId;
            if (accountIndex == 0) {
                if (brokerid == 3) {
                    dropListHtml = "<span class='typeimgbox broker-logo-type'><span class='mark_icon  mark_icon8_3' style='margin-left:5px;' brokerid='3'><img src='/Themes/DefaultClean/Images/broker/3_15_15.png'></span></span><span style='color: #999'>模拟账户</span>";
                }
                else {
                    dropListHtml = "<span class='typeimgbox broker-logo-type'><span class='mark_icon  mark_icon8_3' style='margin-left:5px;'><img src='/Themes/DefaultClean/Images/broker/" + brokerid + ".png' ></span></span>" + data.userAccount.MT4Account;
                    if (data.userAccount.UserType == 2 || data.userAccount.UserType == 0) {
                        dropListHtml += "<span style='color: #999'> - ";

                        if (data.userAccount.BrokerId == 6) {
                            dropListHtml += "mini - ";
                        }
                        dropListHtml += "跟随者</span>";
                    }
                    else if (data.userAccount.UserType == 1) {
                        dropListHtml += "<span style='color: #999'> - ";
                        if (data.userAccount.BrokerId == 6)
                        {
                            dropListHtml += "mini - ";
                        }
                        dropListHtml += "交易员</span>";
                    }
                    //else if (data.userAccount.UserType == 0) {
                    //    dropListHtml +=  "<i class='identity_sb_icon identity_ordinary'></i>";
                    //}
                }
                $("#AccountDropDownList").html(dropListHtml);
                
            }
        }
    });
}

$(document).click(function (e) {
    var ele = e.target;
    if ($(ele).attr("id") == 'AccountDropDownList' || $(ele).hasClass("js_AccountDropI")) {
        return;
    }
    $('#AccountSelectlist').hide();
});